package xdTool

import sysUtil.ResultCode
import sysUtil.ResultJson
import sysUtil.SysAuthSQL
import sysUtil.SysCommUtil
import xdInterface.XdController

class XdWidgetReportController extends XdController{

    def authUtilsService
    def sysDBUtilService

    def index() {}

    @Override
    def detail() {
        return null
    }

    @Override
    def del() {
        def result = ResultJson.resultJson()
        try {
            def id = Long.parseLong( params.id )
            XdWidgetReport old = XdWidgetReport.get(id)
            if(old){

                XdWidgetReportPanel.findAllByRptId(old.id).each {
                    it.delete(flush: true)
                }

                XdWidgetReportParamAct.findAllByRptId(old.id).each {
                    it.delete(flush: true)
                }

                XdWidgetReportPanelAct.findAllByRptId(old.id).each {
                    it.delete(flush: true)
                }

                XdWidgetReportParam.findAllByRptId(old.id).each {
                    it.delete(flush: true)
                }

                old.delete(flush: true)
                result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
                result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
            }else{
                result.put(ResultJson.CODE.name,ResultCode.NOT_EXISTS_ERROR.code)
                result.put(ResultJson.MSG.name,ResultCode.NOT_EXISTS_ERROR.message)
            }
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    @Override
    def edit() {
        def result = ResultJson.resultJson()
        try {
            def name = params.name?:"New Report"
            def id = Long.parseLong(params.id)
            XdWidgetReport xdWidgetReport = XdWidgetReport.get(id)
            XdWidgetReport exist = XdWidgetReport.findByName(name)
            if(exist && xdWidgetReport.id != exist.id){
                result.put(ResultJson.CODE.name,ResultCode.EXISTS_ERROR.code)
                result.put(ResultJson.MSG.name,ResultCode.EXISTS_ERROR.message)
            }else if(!exist){
                xdWidgetReport.setName(name)
                xdWidgetReport.save(flush: true)
                result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
                result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
            }
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    /**
     * 更新布局
     * @return
     */
    @Override
    def editLayout() {
        def result = ResultJson.resultJson()
        try {
            def layout = params.layout?:"1"
            def rptId = Long.parseLong(params.rptId)
            XdWidgetReport xdWidgetReport = XdWidgetReport.get(rptId)

            if(!xdWidgetReport){//不存在
                result.put(ResultJson.CODE.name,ResultCode.EXISTS_ERROR.code)
                result.put(ResultJson.MSG.name,ResultCode.EXISTS_ERROR.message)
            }else{
                def db = sysDBUtilService.getGroovySqlInstance()
                db.withTransaction {
                    db.execute(SysAuthSQL.deleteRptPanelById(rptId))
                    db.execute(SysAuthSQL.deleteRptParamById(rptId))
                }

                xdWidgetReport.setLayout(layout)
                xdWidgetReport.setViewHeader(null)
                xdWidgetReport.setViewBody(null)
                xdWidgetReport.setTempBody(null)
                xdWidgetReport.setTempHeader(null)
                xdWidgetReport.save(flush: true)
                result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
                result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
            }
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }



    @Override
    def save() {
        //1.保存配置表数据到act表-保存前需先将 act表清楚
        //2.解析rpt表tempBody、tempHeader成正式html
        def result = ResultJson.resultJson()
        try {
            def rptId = params?.rptId
            authUtilsService.saveRptTemp2Act(rptId)
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    @Override
    def update() {
        return null
    }

    @Override
    def add() {
        def result = ResultJson.resultJson()
        try {
            def name = params.name?:"New Report"
            XdWidgetReport old = XdWidgetReport.findByName(name)
            if(old){
                result.put(ResultJson.CODE.name,ResultCode.EXISTS_ERROR.code)
                result.put(ResultJson.MSG.name,ResultCode.EXISTS_ERROR.message)
            }else{
                XdWidgetReport xdWidgetReport = new XdWidgetReport(name:name)
                xdWidgetReport.save(flush: true)
                result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
                result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
            }
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    @Override
    def dowLoad() {
        return null
    }

    @Override
    def upLoad() {
        return null
    }

    @Override
    def getOne() {
        def result = ResultJson.resultJson()
        try {
            def rptId =  Long.parseLong(params?.rptId)
            XdWidgetReport xdWidgetReport = XdWidgetReport.get(rptId)
            result.put(ResultJson.DATA.name,SysCommUtil.copyMap(xdWidgetReport))
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"getOne:${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    @Override
    def query() {
        def result = ResultJson.resultJson()
        try {
            def searchStr = params?.searchStr
            int offset = Long.parseLong( params.page ?:"1")
            int max = Long.parseLong(params.limit?:"10")
            def db = sysDBUtilService.getGroovySqlInstance()
            def sql = SysAuthSQL.getWidgetReportSQL(searchStr)
            def data = sysDBUtilService.pageResult(sql,offset,max,db)
            def count = sysDBUtilService.pageCount(sql,db)
            result.put(ResultJson.DATA.name,data)
            result.put(ResultJson.COUNT.name,count)
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    @Override
    def delete() {
        del()
    }

    /**
     * 获取rpt未配置panel清单
     * @return
     */
    def getWidgetReportPanel(){
        def result = ResultJson.resultJson()
        try {
            def rptId =  params?.rptId
            def panelName =  params?.panelName
            int offset = Long.parseLong( params.page ?:"1")
            int max = Long.parseLong(params.limit?:"20")
            def db = sysDBUtilService.getGroovySqlInstance()
            def sql = SysAuthSQL.getWidgetReportPanelSQL(rptId,panelName)

            def data = sysDBUtilService.pageResult(sql,offset,max,db)
            def count = sysDBUtilService.pageCount(sql,db)
            result.put(ResultJson.DATA.name,data)
            result.put(ResultJson.COUNT.name,count)
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }


    /**
     * 获取rpt未配置panel清单
     * param not rela rpt
     * @return
     */
    def getRptNotParam(){
        def result = ResultJson.resultJson()
        try {
            def rptId =  params?.rptId

            def db = sysDBUtilService.getGroovySqlInstance()
            def sql = SysAuthSQL.getWidgetRptParamSQL(rptId,"not")

            def data = sysDBUtilService.pageAllResult(sql,db)
            result.put(ResultJson.DATA.name,data)
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }



    /**
     * 更新html
     * @return
     */
    def updateRptTempHtml(){
        def result = ResultJson.resultJson()
        try {
            def rptId =  Long.parseLong(params?.rptId)
            def field =  String.valueOf(params?.field)
            def script =  params.script?:""

            XdWidgetReport xdWidgetReport = XdWidgetReport.get(rptId)
            if(xdWidgetReport && params?.field){
                xdWidgetReport.setProperty(field,SysCommUtil.String2Clob(script))
                if(field =="tempBody"){
                    authUtilsService.updateRptViewPanelHtml(xdWidgetReport)
                }else{
                    authUtilsService.updateRptViewParamHtml(xdWidgetReport)
                }
                xdWidgetReport.save(flush: true)
            }
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name, ResultCode.TABLE_DATA_SUCCESS.message)
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"updateRptTempHtml:${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    /**
     * add 、del 、order  ：更新rpt 与 panel 的关系
     * @return
     */
    def updateRptPanelRel(){
        def result = ResultJson.resultJson()
        try {
            def rptId =  Long.parseLong(params?.rptId)
            def relType =  String.valueOf(params?.relType)
            def panelId = Long.parseLong(params?.panelId)

            if(relType == "add"){
                XdWidgetReportPanel xdWidgetReportPanel = new XdWidgetReportPanel(rptId: rptId,panelId: panelId,orderNum: 99999999)
                xdWidgetReportPanel.save(flush: true)
                authUtilsService.updateRptPanelOrder(rptId)
            }else if(relType == "del"){
                XdWidgetReportPanel xdWidgetReportPanel = XdWidgetReportPanel.findByPanelIdAndRptId(panelId,rptId)
                if(xdWidgetReportPanel){
                    xdWidgetReportPanel.delete(flush: true)
                    authUtilsService.updateRptPanelOrder(rptId)
                }
            }else if(relType == "-1"){//改变位置
                XdWidgetReportPanel xdWidgetReportPanel = XdWidgetReportPanel.findByPanelIdAndRptId(panelId,rptId)
                int max = XdWidgetReportPanel.findAllByRptId(rptId).orderNum.max()
                int min = XdWidgetReportPanel.findAllByRptId(rptId).orderNum.min()
                int oldNum = xdWidgetReportPanel.orderNum
                int newNum = oldNum + Long.parseLong(relType)
                if(newNum >= min && newNum <= max ){
                    def oldData = XdWidgetReportPanel.findByRptIdAndOrderNum(rptId,newNum)
                    oldData.setOrderNum(oldNum)
                    xdWidgetReportPanel.setOrderNum(newNum)

                    oldData.save(flush: true)
                    xdWidgetReportPanel.save(flush: true)
                }
            }

            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name, ResultCode.TABLE_DATA_SUCCESS.message)
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"updateRptPanelRel:${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    /**
     * 更新 rpt-param 关系
     */
    def updateRptParamRel(){
        def result = ResultJson.resultJson()
        try {
            Long rptId =  Long.parseLong(params?.rptId)
            def relType =  String.valueOf(params?.relType)

            if(relType == "add"){

                def db = sysDBUtilService.getGroovySqlInstance()
                def sql = SysAuthSQL.getWidgetRptParamSQL(rptId,"not")
                def data = sysDBUtilService.pageAllResult(sql,db)
                if(data){
                    data.each {
                        XdWidgetReportParam xdWidgetReportParam = new XdWidgetReportParam(rptId: rptId,paramId: it.ID,classFlag: it.CLASS_FLAG, orderNum: 999999)
                        xdWidgetReportParam.save(flush: true)
                    }
                    authUtilsService.updateRptParamOrder(rptId)
                }
            }else if(relType == "del"){

                String classFlag = String.valueOf(params.classFlag)
                Long paramId =  Long.parseLong(params.paramId)

                XdWidgetReportParam xdWidgetReportParam = XdWidgetReportParam.findByRptIdAndClassFlagAndParamId(rptId,classFlag,paramId)
                if(xdWidgetReportParam){
                    xdWidgetReportParam.delete(flush: true)
                    authUtilsService.updateRptParamOrder(rptId)
                }
            }else if(relType == "-1"){//改变位置

                String classFlag = String.valueOf(params.classFlag)
                Long paramId =  Long.parseLong(params.paramId)

                XdWidgetReportParam xdWidgetReportParam = XdWidgetReportParam.findByRptIdAndClassFlagAndParamId(rptId,classFlag,paramId)
                int max = XdWidgetReportParam.findAllByRptId(rptId).orderNum.max()
                int min = XdWidgetReportParam.findAllByRptId(rptId).orderNum.min()
                int oldNum = xdWidgetReportParam.orderNum
                int newNum = oldNum + Long.parseLong(relType)
                if(newNum >= min && newNum <= max ){
                    def oldData = XdWidgetReportParam.findByRptIdAndOrderNum(rptId,newNum)
                    oldData.setOrderNum(oldNum)
                    xdWidgetReportParam.setOrderNum(newNum)

                    oldData.save(flush: true)
                    xdWidgetReportParam.save(flush: true)
                }
            }

            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name, ResultCode.TABLE_DATA_SUCCESS.message)
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    /**
     * 获取rpt的整体配置
     */
    def getRptBusinessCfg(){
        def result = ResultJson.resultJson()
        try {
            def rptId =  Long.parseLong(params?.rptId)
            def fromItem = authUtilsService.getRptParamListById(rptId)

            def rptPanels = XdWidgetReportPanel.findAllByRptId(rptId)
            def layUITable = []
            def echart = []
            def actionParam = []
            rptPanels.each {panel ->
                XdWidgetPanel xdWidgetPanel = XdWidgetPanel.get(panel.panelId)
                XdWidget xdWidget = XdWidget?.get(xdWidgetPanel?.xdWidgetId)
                if(xdWidgetPanel &&  xdWidget?.classFlag.indexOf("xd-panel-table")!=-1 ){
                    XdTableCfg xdTableCfg = XdTableCfg.get(xdWidgetPanel.dataId)
                    Map  layTable = xdTableCfg.toLayUiTableModel(params)
                    layUITable.add(layTable)
                }else if(xdWidgetPanel && xdWidget.classFlag.indexOf("xd-panel-echart")!=-1  ){
                    def xml = SysCommUtil.getEchartTempleteXMLFile(panel.panelId).getText()
                    def prodOption =   SysCommUtil.getJSONByNode(xml,"prodoption")
                    prodOption.put(ResultJson.PANEL_ID.name,panel.panelId)
                    def action  =  SysCommUtil.getEchartActionParamByXml(xml)
                    action.put(ResultJson.DOM_ID.name,xdWidgetPanel.label)
                    echart.add(prodOption)
                    actionParam.add(action)
                }
            }
            result.put(ResultJson.TABLE.name,layUITable)
            result.put(ResultJson.FORM_ITEM.name,fromItem)
            result.put(ResultJson.CODE.name,ResultCode.OPT_SUCCESS.code)
            result.put(ResultJson.ECHART.name,echart)
            result.put(ResultJson.ACTION_PARAM.name,actionParam)
            result.put(ResultJson.MSG.name, ResultCode.OPT_SUCCESS.message)
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"getRptBusinessCfg:${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    /**
     * 获取rpt的整体配置
     */
    def getRptBusinessCfgAct(){
        def result = ResultJson.resultJson()
        try {
            def rptId =  Long.parseLong(params?.rptId)
            def fromItem = authUtilsService.getRptParamListActById(rptId)

            def rptPanels = XdWidgetReportPanelAct.findAllByRptId(rptId)
            def layUITable = []
            def echart = []
            def actionParam = []
            rptPanels.each {panel ->
                XdWidgetPanel xdWidgetPanel = XdWidgetPanel.get(panel.panelId)
                XdWidget xdWidget = XdWidget?.get(xdWidgetPanel?.xdWidgetId)
                if(xdWidgetPanel &&  xdWidget.classFlag.indexOf("xd-panel-table")!=-1 ){
                    XdTableCfg xdTableCfg = XdTableCfg.get(xdWidgetPanel.dataId)
                    Map  layTable = xdTableCfg.toLayUiTableModel(params)
                    layUITable.add(layTable)
                }else if(xdWidgetPanel && xdWidget.classFlag.indexOf("xd-panel-echart")!=-1  ){
                    def xml = SysCommUtil.getEchartTempleteXMLFile(panel.panelId).getText()
                    def prodOption =   SysCommUtil.getJSONByNode(xml,"prodoption")
                    prodOption.put(ResultJson.PANEL_ID.name,panel.panelId)
                    def action  =  SysCommUtil.getEchartActionParamByXml(xml)
                    action.put(ResultJson.DOM_ID.name,xdWidgetPanel.label)
                    echart.add(prodOption)
                    actionParam.add(action)
                }
            }

            result.put(ResultJson.WHERE.name,params)//用于二阶报表参数传递
            result.put(ResultJson.TABLE.name,layUITable)
            result.put(ResultJson.FORM_ITEM.name,fromItem)
            result.put(ResultJson.CODE.name,ResultCode.OPT_SUCCESS.code)
            result.put(ResultJson.ECHART.name,echart)
            result.put(ResultJson.ACTION_PARAM.name,actionParam)
            result.put(ResultJson.MSG.name, ResultCode.OPT_SUCCESS.message)
        }catch (Exception e){
            result.put(ResultJson.MSG.name,"getRptBusinessCfg:${e.getStackTrace()}".substring(0,200))
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            e.printStackTrace()
        }finally{
            render result
        }
    }
}
